package ru.sis.shop.servlets;

import java.io.IOException;
import java.net.HttpURLConnection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import ru.sis.shop.model.Item;

/**
 * Controller for all goods items view.
 */
@WebServlet("/item_view")
public final class ItemViewController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
			IOException {
		long id = 0;
		try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (final NumberFormatException e) {
			response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
			return;
		}

		final SessionFactory factory = (SessionFactory) getServletContext().getAttribute("sessionFactory");
		final Session session = factory.openSession();
		try {
			final Item item = (Item) session.get(Item.class, id);

			if (item == null) {
				response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
				return;
			}

			request.setAttribute("item", item);
			final RequestDispatcher dispatcher = request.getRequestDispatcher("item_view.jsp");
			dispatcher.forward(request, response);
		} finally {
			session.close();
		}
	}
}
